package com.gxy.learn.mybatisplus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 插入数据库时自动写入字段
 */
@Slf4j
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
    private final String CREATE_TIME = "createDate";
    private final String UPDATE_TIME = "updateDate";
    private final String DELETE_FLAG = "delFlag";

    /**
     * 插入时自动写入创建时间 创建人
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName(CREATE_TIME, new Date(), metaObject);
        this.setFieldValByName(DELETE_FLAG, 0, metaObject);
    }

    /**
     * 插入时自动写入修改时间 修改人
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
    }
}
